package org.granola.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;

public class ResourceFinder {

	/**
	 * Try to get a resource :
	 * <ul>
	 * <li> relative to the class
	 * <li> absolute path
	 * <li> relative to class base
	 * </ul>
	 * 
	 * @param klass
	 * @param name
	 * @return
	 */
	public static URL getResource(Class<?> klass, String name)
			throws Exception {
		
		// relative to class path
		URL url = klass.getResource(name);
		if (url != null) {
			return url;
		}
		
		// absolute path
		File file = new File(name);
		if (file.exists()) {
			return file.toURI().toURL();
		}
		
		// relative to class base path
		File baseDir = new File(klass
				.getResource(klass.getSimpleName() + ".class").toURI()
				.getPath()).getParentFile();
		file = new File(baseDir, name);
		if (!file.exists()) {
			throw new IllegalArgumentException("Impossible to find '" + name
					+ "' from " + klass.getName());
		}
		return file.toURI().toURL();
	}

	public static String getResourcePath(Class<?> klass, String name)
			throws MalformedURLException, FileNotFoundException {
		String path = null;
		URL url = klass.getResource(path);
		if (url != null && !name.startsWith("/")) {
			path = klass.getName().replaceAll("\\.", "/");
			path = "/" + path.substring(0, path.lastIndexOf("/") + 1) + name;
		}
		if (url == null && !name.startsWith("/")) {
			path = "/" + name;
			url = klass.getResource(path);
			if (url == null) {
				path = klass.getName().replaceAll("\\.", "/");
				path = "/" + path.substring(0, path.lastIndexOf("/") + 1)
						+ name;
				url = klass.getResource(path);
			}
			if (url == null && new File(name).exists()) {
				path = name;
			}
		}
		if (path == null) {
			throw new FileNotFoundException(name);
		}
		return path;
	}
}
